

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/clock.jpg">
  <link rel="icon" href="/img/clock.jpg">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="lingllqs">
  <meta name="keywords" content="爱编程的少侠">
  
    <meta name="description" content="Linux 多线程编程  线程的概念 线程与进程区别 Linux 线程介绍 Linux 线程基本编程 Windows多线程编程  线程的概念  线程的优点   线程的实现时间远晚于进程.最早实现是solaris 上线程,多线程技术已经被许多操作系统 所支持，包括Windows&#x2F;NT，和Linux 使用多线程的理由之一是和进程相比，它是一种非常&quot;节俭&quot;的多任务操作方式。启动 一个">
<meta property="og:type" content="article">
<meta property="og:title" content="Linux线程">
<meta property="og:url" content="https://lingllqs.github.io/archives/918f81df.html">
<meta property="og:site_name" content="少侠的博客">
<meta property="og:description" content="Linux 多线程编程  线程的概念 线程与进程区别 Linux 线程介绍 Linux 线程基本编程 Windows多线程编程  线程的概念  线程的优点   线程的实现时间远晚于进程.最早实现是solaris 上线程,多线程技术已经被许多操作系统 所支持，包括Windows&#x2F;NT，和Linux 使用多线程的理由之一是和进程相比，它是一种非常&quot;节俭&quot;的多任务操作方式。启动 一个">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-02-23T08:42:04.000Z">
<meta property="article:modified_time" content="2023-09-16T15:49:21.980Z">
<meta property="article:author" content="lingllqs">
<meta property="article:tag" content="爱编程的少侠">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>Linux线程 - 少侠的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"lingllqs.github.io","root":"/","version":"1.9.5","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"f8764fb24a6f40d929b789fbec8ad09b","google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?f8764fb24a6f40d929b789fbec8ad09b";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  
    <!-- Google tag (gtag.js) -->
    <script async>
      if (!Fluid.ctx.dnt) {
        Fluid.utils.createScript("https://www.googletagmanager.com/gtag/js?id=", function() {
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '');
        });
      }
    </script>
  

  

  

  

  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>炸天帮</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/" target="_self">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" rel="external nofollow noreferrer" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" rel="external nofollow noreferrer" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Linux线程"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-02-23 16:42" pubdate>
          2023年2月23日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          5.9k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          50 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">Linux线程</h1>
            
            
              <div class="markdown-body">
                
                <h2 id="Linux-多线程编程">Linux 多线程编程</h2>
<ul>
<li>线程的概念</li>
<li>线程与进程区别</li>
<li>Linux 线程介绍</li>
<li>Linux 线程基本编程</li>
<li>Windows多线程编程</li>
</ul>
<h3 id="线程的概念">线程的概念</h3>
<ol>
<li>线程的优点</li>
</ol>
<blockquote>
<p>线程的实现时间远晚于进程.最早实现是solaris 上线程,多线程技术已经被许多操作系统 所支持，包括Windows/NT，和Linux<br>
使用多线程的理由之一是和进程相比，它是一种非常&quot;节俭&quot;的多任务操作方式。启动<br>
一个新的进程必须分配给它独立的地址空间，建立众多的数据表来维护它的代码段、<br>
堆栈段和数据段，这是一种&quot;昂贵&quot;的多任务工作方式。而运行于一个进程中的多个线<br>
程，它们彼此之间使用相同的地址空间，共享大部分数据，.<br>
线程间方便的通信机制 ,由于同一进程下的线程之间共享数据空间，所以一个线程的<br>
数据可以直接为其它线程所用，这不仅快捷，而且方便。<br>
多线程的程序会提高响应速度.特别是GUI<br>
使多CPU系统更加有效。操作系统会保证当线程数不大于CPU数目时，不同的线程运<br>
行于不同的CPU上。<br>
改善程序结构。一个既长又复杂的进程可以考虑分为多个线程，成为几个独立或半独<br>
立的运行部分，这样的程序会利于理解和修改。</p>
</blockquote>
<ol start="2">
<li>Linux 对线程的支持</li>
</ol>
<blockquote>
<p>Linux系统下的多线程遵循POSIX线程接口 ,所以被称为pthread.<br>
pthread是目前Linux平台上使用最为广泛的线程库，由Xavier Leroy 负责开发完成，并已<br>
绑定在GLIBC中发行。<br>
Linux内核并不支持真正意义上的线程，LinuxThreads是用与普通进程具有同样内核调度<br>
视图的轻量级进程来实现线程支持的。这些轻量级进程拥有独立的进程id，在进程调度、<br>
信号处理、IO等方面享有与普通进程一样的能力。<br>
因此一个多线程程序用ps查看,可以看到每一个线程也占用一行显行<br>
LinuxThreads 项目最初将多线程的概念引入了 Linux，但是LinuxThreads 并不完全遵<br>
守 POSIX 线程标准。一个更新的Native POSIX Thread Library（NPTL）正在应用开来.<br>
由于历史原因.有大量应用采用pthread,很多嵌入式平台也只是支持pthread库.本节教材<br>
也将采用pthread作为线程应用库</p>
</blockquote>
<h3 id="线程与进程区别">线程与进程区别</h3>
<blockquote>
<p>进程是一个应用程序独立运行单位,而线程不能独立存在,必须由在一个进程创建.<br>
在Windows下,线程和进程都是内核内置的机制,而Linux一开始就在内核创建进程机制,直<br>
到2.2后才开始加入线程实现,到2.6才才稳定<br>
Linux的线程库是基于应用库实现,远没有基于内核的进程稳定.在重负衡的关键任务的服<br>
务器,往往采用多进程机制实现.</p>
</blockquote>
<ul>
<li>进程空间</li>
</ul>
<blockquote>
<p>每个进程都独立占有4G的独立虚拟内存空间,各自拥有完整的堆,栈,代码段和数据段<br>
在调用fork时,子进程完全从父进程4G空间复制过来<br>
这意味,现有堆栈的局域变量,全局变量等的值完全一样<br>
在fork后,父子进程各自独立修改自己空间的变量<br>
两者即便是有同名变量,各自值也是独立修改<br>
进程间,包括父子进程之间交换数据必须需要进程间通讯机制来实现</p>
</blockquote>
<ul>
<li>线程空间</li>
</ul>
<blockquote>
<p>同一个进程创建的所有线程之间共享创建进程的空间,即大家拥有相同2G空间,当一个线<br>
程修改一个全局变量后,另一个线程也访问得到这个值<br>
因此在多线程并发修改某个值,必须要进行加锁保护,以便能正确修改值,</p>
</blockquote>
<h3 id="Linux-线程基本编程">Linux 线程基本编程</h3>
<ol>
<li>Linux 线程的基本函数</li>
</ol>
<blockquote>
<p>常用线程函数<br>
pthread_create 创建一个线程<br>
pthead_exit 线程自行退出<br>
pthread_join 其它线程等待某一个线程退出<br>
pthread_cancel 其它线程强行杀死某一个线程<br>
pthread线程库的使用<br>
glib库内置了线程库.<br>
在源码中使用头文件 pthread.h<br>
用gcc链接时加上 –lpthread 选项,链接线程库</p>
</blockquote>
<ol>
<li>pthread_create 创建一个线程</li>
</ol>
<ul>
<li>线程的创建</li>
</ul>
<blockquote>
<p>int pthread_create(pthread_t *thread,pthread_attr_t *attr,<br>
void *(*start_routine)(void *), void *arg);</p>
</blockquote>
<blockquote>
<p>pthread_create创建一个线程,thread是用来表明创建线程的ID,attr指出线程创建时<br>
候的属性,我们用NULL来表明使用缺省属性.start_routine函数指针是线程创建成功<br>
后开始执行的函数,arg是这个函数的唯一一个参数.表明传递给start_routine的参数.<br>
一个进程中的每个线程都由一个线程ID（thread ID）标识，其数据类型是pthread_t<br>
（常常是unsigned int）。如果新的线程创建成功，其ID将通过thread指针返回。</p>
</blockquote>
<ol start="2">
<li>pthread_exit 退出一个线程</li>
</ol>
<blockquote>
<p>线程的退出有两种方式,一种线程函数运行结束,比如到函数结尾或用return退出.线程自<br>
然结束.这是最常用的方式.<br>
调用pthread_exit退出.<br>
void pthread_exit(void *retval);<br>
退出当前线程,并且设线程的返回值为retval<br>
返回值可以用pthread_join取得</p>
</blockquote>
<ol start="3">
<li>pthread_join 等待线程退出</li>
</ol>
<blockquote>
<p>int pthread_join(pthread *thread,void **thread_return);<br>
这个函数类似于waitpid,pthread_join是当前线程在等待另一个线程结束,只不过前者<br>
是在等待一个进程退出,后者在等待一个线程编号为thread的线程退出.<br>
当一个线程调用pthread_exit时,如果其它线程或进程使用了pthead_join在等待这个线<br>
程结束,那线程ID和退出状态将一直保留到pthread_join执行时.<br>
pthread_exit()设定的返回值,或者return的返回值可以被pthread_join的thread_return捕获</p>
</blockquote>
<ol start="4">
<li>pthread_cancel 杀死一个线程</li>
</ol>
<blockquote>
<p>pthread_cancel(pthread_t thread) ;<br>
当前线程将杀死线程ID为thread的线程<br>
pthread_exit()是当前线程自已退出,而pthread_cancel是其它线程杀死别的线程</p>
</blockquote>
<ol start="2">
<li>关于线程的生存周期</li>
</ol>
<blockquote>
<p>程序的主进程默认为主线程.<br>
一个子线程的生存周期由pthread_create 创建后开始,<br>
一直到线程函数执行完毕,或者执行到pthread_exit 处.线程的生命到此结束.<br>
其它线程可以用pthread_cancel强制杀死另一线程.<br>
主线程退出,(比如在主函数里调用exit),它的子线程无论是否执行完毕,都会随主线程退出 而一同消失.<br>
所以在一般在主函数里,必须要判断的一下子线程是否真正退出,如是方可以把主线程<br>
退出.否则很可能造成程序结果不正确<br>
判断线程是否结束最简单的方法是在主线程的退出用 pthread_join来等待子线程退 出即可</p>
</blockquote>
<p>线程示例</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdio.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;pthread.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">define</span> RUN_TIME 10</span><br><br><span class="hljs-comment">/* 定义线程函数*/</span><br><span class="hljs-type">void</span> * <span class="hljs-title function_">thread</span><span class="hljs-params">(<span class="hljs-type">void</span> * arg)</span><br>&#123;<br>    <span class="hljs-type">int</span> i;<br>    <span class="hljs-keyword">for</span>(i=<span class="hljs-number">0</span>;i&lt;RUN_TIME;i++)<br>    &#123;<br>        <span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;This is a pthread.\n&quot;</span>); sleep(<span class="hljs-number">1</span>);<br>    &#125;<br>&#125;<br><br><span class="hljs-type">int</span> <span class="hljs-title function_">main</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span><br>&#123;<br>    <span class="hljs-type">pthread_t</span> id;<br>    <span class="hljs-type">int</span> i,ret;<br>    <span class="hljs-comment">/* 创建一个线程 */</span><br>    ret=pthread_create(&amp;id,<span class="hljs-literal">NULL</span>,(<span class="hljs-type">void</span> *) thread,<span class="hljs-literal">NULL</span>);<br>    <span class="hljs-keyword">if</span>(ret!=<span class="hljs-number">0</span>)&#123;<br>    <span class="hljs-built_in">printf</span> (<span class="hljs-string">&quot;Create pthread error!\n&quot;</span>);<br>    <span class="hljs-built_in">exit</span> (<span class="hljs-number">1</span>);<br>&#125;<br></code></pre></td></tr></table></figure>
<ol start="3">
<li>修改线程的属性</li>
</ol>
<blockquote>
<p>绝大部分情况下,创建线程使用了默认参数，即将pthread_create函数的第二个参数设为NULL。<br>
在特殊情况才需要设置线程属性pthread_attr_t,<br>
属性对象主要包括是否绑定、是否分离、堆栈地址、堆栈大小、优先级。<br>
默认的属性为非绑定、非分离、缺省1M的堆栈、与父进程同样级别的优先级。<br>
初始化线程属性<br>
pthread_attr_init(&amp;attr);<br>
这个函数必须在pthread_create函数之前调用<br>
设置线程绑定特性<br>
pthread_attr_setscope<br>
设置线程绑定状态的函数为pthread_attr_setscope，它有两个参数，第一个是指向属<br>
性结构的指针，第二个是绑定类型，它有两个取值：PTHREAD_SCOPE_SYSTEM（绑<br>
定的）和PTHREAD_SCOPE_PROCESS（非绑定的）。下面的代码即创建了一个绑<br>
定的线程。<br>
设置线程的优先级<br>
它存放在结构sched_param<br>
用函数pthread_attr_getschedparam和函数pthread_attr_setschedparam进行存<br>
放，一般说来，我们总是先取优先级，对取得的值修改后再存放回去</p>
</blockquote>
<p><em>修改线程属性实例</em></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;pthread.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;sched.h&gt;</span></span><br><br><span class="hljs-type">pthread_attr_t</span> attr;<br><span class="hljs-type">pthread_t</span> tid;<br><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">sched_param</span> <span class="hljs-title">param</span>;</span><br><span class="hljs-type">int</span> newprio=<span class="hljs-number">20</span>;<br><br>pthread_attr_init(&amp;attr);<br>pthread_attr_setscope(&amp;attr, PTHREAD_SCOPE_SYSTEM);<br>pthread_attr_getschedparam(&amp;attr, &amp;param);<br><br>param.sched_priority=newprio; <span class="hljs-comment">//设置优先级</span><br>pthread_attr_setschedparam(&amp;attr, &amp;param);<br>pthread_create(&amp;tid, &amp;attr, (<span class="hljs-type">void</span> *)myfunction, myarg);<br><br><span class="hljs-keyword">for</span>(i=<span class="hljs-number">0</span>;i&lt;RUN_TIME;i++)<br>&#123;<br>    <span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;This is the main process.\n&quot;</span>);<br>    sleep(<span class="hljs-number">1</span>);<br>&#125;<br><span class="hljs-comment">/* 等待线程退出 */</span><br>pthread_join(id,<span class="hljs-literal">NULL</span>);<br><span class="hljs-keyword">return</span> (<span class="hljs-number">0</span>);<br>&#125;<br></code></pre></td></tr></table></figure>
<h3 id="Windows线程支持">Windows线程支持</h3>
<ol>
<li>Windows线程</li>
</ol>
<ul>
<li>Windows线程机制非常类似Linux的线程调用.<br>
– 包含头文件 &lt;process.h&gt;<br>
– 表示线程数据结构 unsigned long<br>
– 创建一个线程 _beginthread</li>
</ul>
<blockquote>
<p>unsigned long _beginthread( void( __cdecl *start_address )( void * ),<br>
unsigned stack_size, void *arglist );</p>
</blockquote>
<ul>
<li>第一个参数为线程函数,第二个函数为堆栈空间,取0由系统分配一个缺省尺寸,第三<br>
是线程函数参数,当线程创建时,arglist 将传送给线程函数<br>
– 线程函数执行完毕,将自动销毁线程,或提前用_endthread()进行销毁<br>
– 链接时时候需要使用LIBMT.LIB</li>
</ul>
<ol start="2">
<li>CreateThread:创建一个线程</li>
</ol>
<ul>
<li>
<p>CreateThread()实现在Windows内核,即kernel.dll的实现,_beginthread实际上是调用</p>
</li>
<li>
<p>CreateThread()来创建一个线程</p>
</li>
<li>
<p>如果想对线程做更复杂的控制,可以使用CreateThread来创建一个线程.<br>
– CreateThread创建线程数据结构用handle表示<br>
– 用CreateThread创建可以对线程做更多控制,如挂起,等待…</p>
</li>
</ul>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;process.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdio.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdlib.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;windows.h&gt;</span></span><br><br><span class="hljs-type">static</span> <span class="hljs-type">void</span> <span class="hljs-title function_">thread_func</span><span class="hljs-params">(<span class="hljs-type">void</span> * arg)</span><br>&#123;<br>    <span class="hljs-type">int</span> i,count = (<span class="hljs-type">int</span>)arg;<br><br>    <span class="hljs-built_in">fprintf</span>(<span class="hljs-built_in">stderr</span>,<span class="hljs-string">&quot;count =%d,pid=%d\n&quot;</span>,count,getpid());<br><br>    <span class="hljs-keyword">for</span>(i=<span class="hljs-number">0</span>; i&lt; count ; i++)<br>    &#123;<br>        <span class="hljs-built_in">fprintf</span>(<span class="hljs-built_in">stderr</span>,<span class="hljs-string">&quot; I am a thread %d\n&quot;</span>,count);<br>        Sleep(<span class="hljs-number">1000</span>);<br>    &#125;<br><br>&#125;<br><br><span class="hljs-type">int</span> <span class="hljs-title function_">main</span><span class="hljs-params">()</span><br>&#123;<br>    _beginthread(thread_func,<span class="hljs-number">0</span>,(<span class="hljs-type">void</span> *)<span class="hljs-number">10</span>);<br>    _beginthread(thread_func,<span class="hljs-number">0</span>,(<span class="hljs-type">void</span> *)<span class="hljs-number">20</span>);<br><br>    getchar();<br>&#125;<br></code></pre></td></tr></table></figure>
<ol start="3">
<li>WaitForSingleObject</li>
</ol>
<blockquote>
<p>WaitForSingleObject从字面意思上可以理解为等待单个对象,在Windows下,线程,互斥量,<br>
事件等各个操作系统对象都用使用这个参数.<br>
如果是一个线程被等待,相当于是pthread_join的功能,在等待一个线程运行完毕<br>
WaitForSingleObject的优点之一是可以带超时参数,即到了指定时间未等想要结果,可以<br>
结束等待,而pthread_join无此功能.<br>
用宏定义INFINITE 表示无穷大,即无限等待下去<br>
WaitForSingleObject(thread, INFINITE);</p>
</blockquote>
<p><em>思考</em></p>
<blockquote>
<p>同样程序你可以用多线程和多进程模型来实现,你是如何权衡采用哪一种体系结构的?<br>
在程序设计中,对公共资源(比如缓冲区等)的操作和访问经常需要使用锁来进行保护,<br>
但在大并发系统中过多的锁会导致效率很低,通常有那些方法可以尽量避免或减少锁的使用?</p>
</blockquote>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs c">HANDLE <span class="hljs-title function_">CreateThread</span><span class="hljs-params">(</span><br><span class="hljs-params">LPSECURITY_ATTRIBUTES lpThreadAttributes, <span class="hljs-comment">// SD</span></span><br><span class="hljs-params">DWORD dwStackSize, <span class="hljs-comment">// initial stack size</span></span><br><span class="hljs-params">LPTHREAD_START_ROUTINE lpStartAddress, <span class="hljs-comment">// thread function</span></span><br><span class="hljs-params">LPVOID lpParameter, <span class="hljs-comment">// thread argument</span></span><br><span class="hljs-params">DWORD dwCreationFlags, <span class="hljs-comment">// creation option</span></span><br><span class="hljs-params">LPDWORD lpThreadId <span class="hljs-comment">// thread identifier</span></span><br><span class="hljs-params">)</span>;<br></code></pre></td></tr></table></figure>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Linux线程</div>
      <div>https://lingllqs.github.io/archives/918f81df.html</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>lingllqs</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年2月23日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/" rel="external nofollow noreferrer">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/archives/7a214a3b.html" title="英文缩写含义">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">英文缩写含义</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/archives/49618a82.html" title="Linux网络编程">
                        <span class="hidden-mobile">Linux网络编程</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"ZtaCuooNxUcOqZ44oEeRZvpa-gzGzoHsz","appKey":"ZQm92JiXmMQqpk6hi7Zqoi0w","path":"window.location.pathname","placeholder":null,"avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":true,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":true},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  


  
  









    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  
      <script>
        if (!window.MathJax) {
          window.MathJax = {
            tex    : {
              inlineMath: { '[+]': [['$', '$']] }
            },
            loader : {
              load: ['ui/lazy']
            },
            options: {
              renderActions: {
                insertedScript: [200, () => {
                  document.querySelectorAll('mjx-container').forEach(node => {
                    let target = node.parentNode;
                    if (target.nodeName.toLowerCase() === 'li') {
                      target.parentNode.classList.add('has-jax');
                    }
                  });
                }, '', false]
              }
            }
          };
        } else {
          MathJax.startup.document.state(0);
          MathJax.texReset();
          MathJax.typeset();
          MathJax.typesetPromise();
        }

        Fluid.events.registerRefreshCallback(function() {
          if ('MathJax' in window && MathJax.startup.document && typeof MathJax.startup.document.state === 'function') {
            MathJax.startup.document.state(0);
            MathJax.texReset();
            MathJax.typeset();
            MathJax.typesetPromise();
          }
        });
      </script>
    

  <script  src="https://lib.baomitu.com/mathjax/3.2.2/es5/tex-mml-chtml.js" ></script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
